#!/bin/bash

# Copyright (c) 2019 The STE||AR-Group
#
# SPDX-License-Identifier: BSL-1.0
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

# ----------------------------------------------------------------
# simple pre commit hook script to check that *.cpp and *.hpp files 
# are correctly clang-formatted and that CMakeLists.txt and *.cmake
# files are cmake-formatted

# To use this hook, you must have clang-format and cmake-format
# installed on your system

# To install this hook, copy this file to your git hooks as follows
# cp tools/pre-commit .git/hooks/pre-commit
# chmod +x .git/hooks/pre-commit

# @todo : add support for the hpx inspect tool to be run as well

red=$(tput setaf 1)
green=$(tput setaf 2)
yellow=$(tput setaf 3)
blue=$(tput setaf 4)
normal=$(tput sgr0)

cxxfiles=()
for file in `git diff --cached --name-only --diff-filter=ACMRT | grep -E "\.(cpp|hpp)$"`; do
    if ! cmp -s <(git show :${file}) <(git show :${file}|clang-format -style=file); then
        cxxfiles+=("${file}")
    fi
done

cmakefiles=()
for file in `git diff --cached --name-only --diff-filter=ACMRT | grep -E "(CMakeLists\.txt|\.cmake)$"`; do
    tmpfile=$(mktemp /tmp/cmake-check.XXXXXX)
    git show :${file} > $tmpfile
    cmake-format -c $(pwd)/.cmake-format.py -i $tmpfile
    if ! cmp -s <(git show :${file}) <(cat $tmpfile); then
        cmakefiles+=("${file}")
    fi
    rm $tmpfile
done

returncode=0

if [ -n "${cxxfiles}" ]; then
    printf "# ${blue}clang-format ${red}error pre-commit${normal} : To fix run the following (use git commit ${yellow}--no-verify${normal} to bypass)\n"
    for f in "${cxxfiles[@]}" ; do
        rel=$(realpath --relative-to $GIT_PREFIX $f)
        printf "clang-format -i %s\n" "$rel"
    done
    returncode=1
fi

if [ -n "${cmakefiles}" ]; then
    printf "# ${green}cmake-format ${red}error pre-commit${normal} : To fix run the following (use git commit ${yellow}--no-verify${normal} to bypass)\n"
    for f in "${cmakefiles[@]}" ; do
        rel=$(realpath --relative-to $GIT_PREFIX $f)
        printf "cmake-format -i %s\n" "$rel"
    done
    returncode=1
fi

exit $returncode
